//
//  ExcahngeMallViewController.m
//  Consume100
//
//  Created by eliot on 16/3/24.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "ExcahngeMallViewController.h"
#import "GoodsFirstTableViewCell.h"
#import "ExvhangeMallTableViewCell.h"
#import "EXcahngeMallSecondTableViewCell.h"
#import "ChangePurchaeseTableViewCell.h"
#import "RichAreaViewController.h"
#import "ExchangeHistoryTableViewController.h"
#import "UIImageView+WebCache.h"
#import "GoodsDetailViewController.h"
#import "SubmitDetialTableViewController.h"
#import "MJRefresh.h"
@interface ExcahngeMallViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableVIewTop;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic ,strong) NSTimer *timer;

/** 滚动页点*/
@property (nonatomic ,strong) UIPageControl *page;
/** 滚动视图*/
@property (nonatomic, strong) UIScrollView *sc;
/** 滚动图片 数组*/
@property (nonatomic, strong) NSMutableArray *imageArray;

/** 分区图片 数组*/
@property (nonatomic, strong) NSArray *categoryArray;

/** 换购记录 数组*/
@property (nonatomic, strong) NSArray *makeExchangeArray;

/** 热门换购 数组*/
@property (nonatomic, strong) NSArray *hotExchangeArray;

@end

@implementation ExcahngeMallViewController
static int page = 1;
- (void)dealloc {
    page = 1;
}
-(NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}


- (UIScrollView *)sc {
    if (!_sc) {
        _sc = [[UIScrollView alloc] init];
    }
    return _sc;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        [self setMyScrollView];
        return self.sc;
    }else {
        
        return nil;
    }
}

-(UIPageControl *)page {
    if (!_page) {
        _page = [[UIPageControl alloc] init];
        [self.tableView addSubview:_page];
        [_page mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(self.view.frame.size.width);
            make.top.mas_equalTo(self.sc.frame.size.height - 20);
            make.height.mas_equalTo(20);
        }];
        [_page setBackgroundColor:[UIColor clearColor]];
        [_page setAlpha:1];
    }
    return _page;
}


/** 设置滚动视图*/
- (void)setMyScrollView {
    self.sc.showsHorizontalScrollIndicator = NO;
    self.sc.frame = CGRectMake(0, 0, Width, 214/320.0*Width);
    //创建页点
    [self createsCrollView:nil];
}


#pragma ------创建视图区域----------
//创建滚动视图区域
- (void)createsCrollView:(id)sender {
    //设置委托
    self.sc.delegate = self;
    //将是否取消对内容视图触摸的反应设为NO
    self.sc.canCancelContentTouches = NO;
    //设置滚动条类型
    // self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否可以缩放
    self.sc.scrollEnabled = YES;
    //是否可以进行页面切换
    self.sc.pagingEnabled = YES;
    NSUInteger page = 0;//为了记录页数
    int originX = 0;
    //填充滑动视图内容
    for (NSDictionary *imageDic in self.imageArray) {
        //首先创建一个视图
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectZero];
        imageview.contentMode = UIViewContentModeScaleAspectFit;
        imageview.contentMode = UIViewContentModeScaleToFill;
        //为这个图片设置适当位置
        CGRect rect ;
        rect.origin.x = originX;
        rect.origin.y = 0;
        rect.size.width = Width;
        rect.size.height = 214/320.0*Width;
        imageview.frame = rect;
        //设置图片为背景
        [imageview sd_setImageWithURL:[NSURL URLWithString:imageDic[@"img"]]];
        //添加到视图中
        [self.sc addSubview:imageview];
        //确定下张图片开始的x坐标
        originX += Width;
        //记录页数
        page++;
    }
    //设置总页数
    self.page.numberOfPages = page;
    //设置默认页为首页
    self.page.currentPage = 0;
    self.page.tag = 100;
    //为页数控制关联方法
    [self.page addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    //显示适当区域
    [self.sc setContentSize:CGSizeMake(originX, 214/320.0*Width)];
}
- (void)repartScroll {
    if (self.page.currentPage == self.imageArray.count - 1) {
        self.page.currentPage = 0;
        [self.sc setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else{
        self.page.currentPage = self.page.currentPage + 1;
    }
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = Width;
    rect.size.height = 214/320.0*Width;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//点击小点切换页面
- (void)changePage:(id)sender {
    //创建一个区域
    CGRect rect;
    rect.origin.x = self.page.currentPage * self.sc.frame.size.width;
    rect.origin.y = 0;
    rect.size.width = self.sc.frame.size.width;
    rect.size.height = self.sc.frame.size.height;
    //设置滚动视图的可视区域
    [self.sc scrollRectToVisible:rect animated:YES];
    
}

//重写滑动结束后的反应，就是把pageConteol的当前页跟随滑动而动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //取滚动视图区域的宽
    float orginX = self.sc.frame.size.width;
    //利用当前视图显示区域到view.frame的偏移量，来换算获取当前处在第几页
    int page = ((self.sc.contentOffset.x - orginX))/orginX +1;
    //当前页改为这一页。
    self.page.currentPage = page;
}



//页面将要进入前台，开启定时器
-(void)viewWillAppear:(BOOL)animated
{
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"ExvhangeMallTableViewCell" bundle:nil] forCellReuseIdentifier:@"ExvhangeMallTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EXcahngeMallSecondTableViewCell" bundle:nil] forCellReuseIdentifier:@"EXcahngeMallSecondTableViewCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"ChangePurchaeseTableViewCell" bundle:nil] forCellReuseIdentifier:@"ChangePurchaeseTableViewCell"];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.tableView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.75 target:self selector:@selector(repartScroll) userInfo:nil  repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    
    /** 设置刷新*/
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;

    /** 兑换商城数据*/
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@cashShopIndex.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //NSString *err = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{

            self.imageArray = [NSMutableArray arrayWithArray:dddic[@"bannersJson"]];
            
            self.categoryArray = dddic[@"shopCategorysJson"];
            
            self.makeExchangeArray = dddic[@"shopOrdersJson"];
            
            self.hotExchangeArray = dddic[@"pagerShopProductJson"];
 
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];

}

/** 上拉加载更多*/
- (void)loadMoreData {
    page += 1;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page]};
    NSString *baseUrl = [NSString stringWithFormat:@"%@cashShopIndex.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            [self.hotExchangeArray arrayByAddingObjectsFromArray:dddic[@"pagerShopProductJson"]];
            
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2 + self.hotExchangeArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 0;
            break;
        case 1:
        {
            if (self.makeExchangeArray.count > 3) {
                return 5;
            }else {
                return 2 + self.makeExchangeArray.count;
            }
        }
            break;
        case 2:
            return 2;
            break;
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.showsVerticalScrollIndicator = NO;
    if (indexPath.section == 0) {
        return nil;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            ExvhangeMallTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExvhangeMallTableViewCell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
            [cell.btn4 addTarget:self action:@selector(clickBtn4:) forControlEvents:UIControlEventTouchUpInside];
            [cell.btn3 addTarget:self action:@selector(clickBtn4:) forControlEvents:UIControlEventTouchUpInside];
            [cell.btn2 addTarget:self action:@selector(clickBtn4:) forControlEvents:UIControlEventTouchUpInside];
            [cell.btn1 addTarget:self action:@selector(clickBtn4:) forControlEvents:UIControlEventTouchUpInside];
            cell.btn1.tag = 0;
            cell.btn2.tag = 1;
            cell.btn3.tag = 2;
            cell.btn4.tag = 3;
            for (int i =  0; i< self.categoryArray.count; i++) {
                NSDictionary *tempDic = self.categoryArray[i];
                
                if (i == 0) {
                    [cell.iv1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@",tempDic[@"img"]]]];
                }
                if (i == 1) {
                    [cell.iv2 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@",tempDic[@"img"]]]];
                }
                if (i == 2) {
                    [cell.iv3 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@",tempDic[@"img"]]]];
                }
                if (i == 3) {
                    [cell.iv4 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@",tempDic[@"img"]]]];
                }
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if (indexPath.row == 1){
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFirst"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellFirst"];
                cell.textLabel.text = @"换购记录";
                cell.detailTextLabel.text = @"查看更多";
                UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrows"]];
                iv.frame = CGRectMake(0, 0, 12, 12);
                iv.contentMode = UIViewContentModeScaleAspectFit;
                cell.accessoryView = iv;
                cell.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }else {
            EXcahngeMallSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EXcahngeMallSecondTableViewCell" forIndexPath:indexPath];
            NSArray *temArr = self.makeExchangeArray[indexPath.row - 2];

            cell.titleLb.text = temArr[1];
            cell.nameLb.text = temArr[0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    }else if (indexPath.section == 2){
        if (indexPath.row == 0){
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFirst"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellFirst"];
                cell.textLabel.text = @"热门换购";
                cell.detailTextLabel.text = @"查看更多";
                UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrows"]];
                iv.frame = CGRectMake(0, 0, 12, 12);
                iv.contentMode = UIViewContentModeScaleAspectFit;
                cell.accessoryView = iv;
                cell.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }else {
            ChangePurchaeseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChangePurchaeseTableViewCell" forIndexPath:indexPath];
            [cell.exchangeBtn addTarget:self action:@selector(firstExchangeBtn) forControlEvents:UIControlEventTouchUpInside];
            cell.exchangeBtn.layer.cornerRadius = 14;
            cell.exchangeBtn.layer.masksToBounds = YES;
            NSDictionary *tempDic = self.hotExchangeArray[0];
            
            [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:tempDic[@"img"]]];
            cell.titleLb.text = tempDic[@"name"];
            cell.descLb.text = tempDic[@"putParameter"];
            cell.exchangePriceLb.text = [NSString stringWithFormat:@"%ld",[tempDic[@"orgPrice"] longValue]];
            cell.priceLb.text = [NSString stringWithFormat:@"%ld",[tempDic[@"price"] longValue]];
            cell.titleLb.numberOfLines = 0;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            
        
    }else {
        ChangePurchaeseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChangePurchaeseTableViewCell" forIndexPath:indexPath];
        [cell.exchangeBtn addTarget:self action:@selector(otherExchangeBtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.exchangeBtn.tag = indexPath.section;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.exchangeBtn.layer.cornerRadius = 14;
        cell.exchangeBtn.layer.masksToBounds = YES;
        cell.titleLb.numberOfLines = 0;
        NSDictionary *tempDic = self.hotExchangeArray[indexPath.section - 2];
        [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:tempDic[@"img"]]];
        cell.titleLb.text = tempDic[@"name"];
        cell.descLb.text = tempDic[@"putParameter"];
        cell.exchangePriceLb.text = [NSString stringWithFormat:@"%ld",[tempDic[@"orgPrice"] longValue]];
        cell.priceLb.text = [NSString stringWithFormat:@"%ld",[tempDic[@"price"] longValue]];
        cell.titleLb.numberOfLines = 0;
        return cell;
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 0;
    }else if(indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 173/106.0 * (Width -3)/3;
        }else if (indexPath.row == 1){
            return 44;
        }else {
            return 68;
        }
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            return 44;
        }else {
            return 150;
        }
    }else {
        return 150;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 214/320.0*Width;
    }else if (section == 1 ) {
        return 4;
    }else if (section == 2) {
        return 0;
    }else {
        return 8;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            ExchangeHistoryTableViewController *vc = [ExchangeHistoryTableViewController CreatExchangeSucceedViewController];
            [self creatNav:vc];
        }
    }else if (indexPath.section == 2) {
        if (indexPath.row == 1) {
            GoodsDetailViewController *vc = [GoodsDetailViewController CreatGoodsDetailViewController];
            NSDictionary *tempDic = self.hotExchangeArray[0];
            
            vc.productId = tempDic[@"id"];
            [self creatNav:vc];
        }
    }else {
        GoodsDetailViewController *vc = [GoodsDetailViewController CreatGoodsDetailViewController];
         NSDictionary *tempDic = self.hotExchangeArray[indexPath.section - 2];
        
        vc.productId = tempDic[@"id"];
        
        [self creatNav:vc];
    }

}

- (void)firstExchangeBtn {
    
    SubmitDetialTableViewController *vc = [SubmitDetialTableViewController CreatSubmitDetialTableViewController];
     vc.dataDic = self.hotExchangeArray[0];
    
    [self.navigationController pushViewController:vc animated:YES];


}

- (void)otherExchangeBtn :(UIButton *)sender {

    SubmitDetialTableViewController *vc = [SubmitDetialTableViewController CreatSubmitDetialTableViewController];
    
     vc.dataDic= self.hotExchangeArray[sender.tag - 2];
    [self.navigationController pushViewController:vc animated:YES];


}


//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self.navigationController pushViewController:view animated:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)dismiss {
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}


- (void)clickBtn4:(UIButton*)sender {
    RichAreaViewController *vc = [RichAreaViewController CreatRichAreaViewController];
    vc.TuHao = (int)sender.tag;
    [self creatNav:vc];
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
